<template>
    <el-space>
        <el-image :src="currentMusic?.image" class=" rounded-lg" style="width:70px;height:70px;" />
        <div class="text-gray-500 ml-2">
            <div>{{ currentMusic?.name }}</div>
            <div class="flex">
                <el-space>
                    <span class="text-xs w-12">{{ currentMusic?.author }}</span>
                    <el-space class="flex items-center">
                        <span class="iconfont cursor-pointer" @click="current--">&#xe63c;</span>
                        <div class=" rounded-full bg-gray-100 flex justify-center items-center cursor-pointer"
                            style="width:30px;height:30px;" @click="onPlay">
                            <span class="iconfont" v-if="!playing">&#xe61c;</span>
                            <span class="iconfont" v-if="playing">&#xe62a;</span>
                        </div>
                        <span class="iconfont cursor-pointer" @click="current++">&#xe63e;</span>
                    </el-space>
                </el-space>
            </div>
        </div>
    </el-space>
</template>
<script setup>
import { ref, watch, onUnmounted, onMounted, nextTick } from 'vue';
import { currentMusic, current } from './music';
import WaveSurfer from 'wavesurfer.js'
const emit = defineEmits(['next', 'pre']);

const playing = ref(false)
let sound;
const onPlay = function () {
    if (!sound) return;
    if (playing.value) {
        sound.pause();
    } else {
        sound.play();
    }
}
watch(() => currentMusic.value, (m) => {
    if (m?.url) {
        if (sound) {
            sound.load(m.url);
        } else {
            nextTick(() => {
                sound = WaveSurfer.create({
                    container: document.getElementById('wavesurfer'),
                    waveColor: 'rgb(153, 153, 153)',
                    progressColor: 'rgb(116, 159, 237)',
                    url: m.url,
                    autoplay: true,
                    height: 60,
                })
                sound.on('click', () => {
                    sound.play();
                });
                sound.on('play', () => {
                    playing.value = true;
                });
                sound.on('pause', () => {
                    playing.value = false;
                });
            })
        }

    }
}, { immediate: true })

// onMounted(() => {
//     add({ name: '默认3', author: '作者3', url: 'http://localhost:3000/api/uploads/uploads/20231114/02d754a80cab77f0aca5347e35bddf32.mp3' })
// })

onUnmounted(() => {
    if (sound) {
        sound.stop();
        sound.destroy();
    };
})
</script>
<style scoped>
.pointer {
    cursor: pointer;
}
</style>